package com.laboratory.stomplearning.handler;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.Map;
import java.util.UUID;

/**
 * 自定义用户名
 */
@Component
public class CustomUserHandshakeHandler extends DefaultHandshakeHandler {

    @Override
    protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {
        String query = request.getURI().getQuery();
        String name = null;
        if (query != null) {
            for (String kv : query.split("&")) {
                String[] p = kv.split("=", 2);
                if (p.length == 2 && "user".equals(p[0])) {
                    name = p[1];
                    break;
                }
            }
        }
        if (name == null || name.isBlank())
            name = "u-" + UUID.randomUUID();

        final String finalName = name;
        return () -> finalName; // 返回一个带 name 的Principal
    }

}
